﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using UNFEventPosting.Models;

namespace UNFEventPosting.Controllers
{
    public class EventController : Controller
    {
        EventsDB _db = new EventsDB();

        public ActionResult Index(int categoryID = -1)
        {
            PopulateCategoryDropDownList(categoryID);
            //
            // Gather the list of events from the database
            // Order the list by start time in ascending order
            // Make sure that the list only includes events that haven't ended yet
            // Try to sort based upon the category ID
            if (categoryID > -1)
            {
                var eventsList = from c in _db.Events
                                 orderby c.StartTime ascending
                                 where c.EndTime >= DateTime.Now
                                 where c.Confirmed == true
                                 where c.CategoryID == categoryID
                                 select c;

                return View(eventsList);
            }
            else
            {
                var eventsList = from c in _db.Events
                                 orderby c.StartTime ascending
                                 where c.EndTime >= DateTime.Now
                                 where c.Confirmed == true
                                 select c;

                return View(eventsList);
            }
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Create()
        {
            PopulateCategoryDropDownList();

            DateTime todayDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

            return View(new Event() { StartTime = todayDate, EndTime = todayDate });
        }

        [HttpPost]
        public ActionResult Create(Event thisEvent)
        {
            try
            {
                //
                // If the model is valid, generate a new primary key
                // Verify that the model has not been confirmed
                // Add and save the model to the database
                // Send an email to the submitter
                // Redirect user to page that will notify them that an email has been sent
                if (ModelState.IsValid)
                {
                    thisEvent.ID = Guid.NewGuid();
                    thisEvent.Confirmed = false;
                    _db.Events.Add(thisEvent);
                    _db.SaveChanges();

                    SendEmail(thisEvent.ID, thisEvent.N_Number);

                    return RedirectToAction("Submitted");
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }

            PopulateCategoryDropDownList(thisEvent.CategoryID);
            return View(thisEvent);
        }

        public ActionResult Submitted()
        {
            return View();
        }

        public void SendEmail(Guid ID, String N_Number)
        {
            //
            // Send the following link      [DomainName]:[PortNumber]/Event/Confirm/[Guid ID]
            // The following link works too [DomainName]:[PortNumber]/Event/Confirm?id=[Guid ID]
            var FromAddress     = new MailAddress(@"UNFEventPosting@gmail.com", "UNF Event Posting");
            var ToAddress       = new MailAddress(N_Number + @"@unf.edu");
            //
            // From a production stand point, this needs to be configurable
            String DomainName      = GetDomainName();
            String FromPassword    = "UNFCOP4813";

            //
            //
            String Subject         = "Confirm Your UNF Event Post";
            String Body            = @"Our records indicate that you just submitted an event for the UNF Event Calendar.\n" +
                "Follow the following link to confirm that you are a student at UNF: http://" + DomainName + "/Event/Confirm/" + ID.ToString();

            var smtp = new SmtpClient
            {
                Host                    = "smtp.gmail.com",
                Port                    = 587,
                EnableSsl               = true,
                DeliveryMethod          = SmtpDeliveryMethod.Network,
                UseDefaultCredentials   = false,
                Credentials             = new NetworkCredential(FromAddress.Address, FromPassword)
            };

            using (var Message = new MailMessage(FromAddress, ToAddress)
            {
                Subject = Subject,
                Body = Body
            })
            {
                smtp.Send(Message);
            }
        }

        private string GetDomainName()
        {
            return "localhost" + GetPortNumber();
        }

        private string GetPortNumber()
        {
            return ":1909";
        }

        public ViewResult Details(Guid ID)
        {
            //
            // Find the event and pass to the view
            Event thisEvent = _db.Events.Find(ID);
            return View(thisEvent);
        }

        [HttpGet]
        public ActionResult Confirm(Guid ID)
        {
            //
            // Find the event and confirm
            Event thisEvent = _db.Events.Find(ID);

            if (thisEvent != null)
            {
                thisEvent.Confirmed = true;
                _db.SaveChanges();
            }

            return RedirectToAction("Index");
        }

        private void PopulateCategoryDropDownList(object selectedCategory = null)
        {
            var categoryQuery = from c in _db.Categories select c;
            ViewBag.CategoryID = new SelectList(categoryQuery, "ID", "Name", selectedCategory);
        }
    }
}
